<template>
  <el-container id="AdminPage">
    <el-header class="top">
      <div class="top">
        <div class="content">
          <div class="title">
            <img :src="icon" alt="">
            <span> ADMIN</span>
          </div>
          <div class="avatar">
            <Avatar></Avatar>
          </div>        
        </div>
      </div>
    </el-header>
    <el-container class="content">
      <el-aside width="200px">
        <div class="nav">
          <el-menu 
            :default-active="activeIndex"
            class="el-menu-demo" 
            mode="vertical" 
            @select="handleSelect"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#ffd04b"
          >
            <el-submenu index="1">
              <template #title>用户</template>              
              <el-menu-item index="1-1">用户列表</el-menu-item>
              <!-- 预留暂未开发 -->
              <el-menu-item index="1-2">信息审核</el-menu-item>
            </el-submenu>
            <el-submenu index="2">
              <template #title>文章</template>
              <el-menu-item index="2-1">文章编辑</el-menu-item>
              <el-menu-item index="2-2">文章管理</el-menu-item>
            </el-submenu>
            <el-submenu index="3">
              <template #title>留言</template>
              <el-menu-item index="3-1">留言列表</el-menu-item>
              <el-menu-item index="3-2">留言投诉</el-menu-item>
            </el-submenu>
            <el-menu-item index="4">友链</el-menu-item>
            <el-submenu index="5">
              <template #title>格言</template>
              <el-menu-item index="5-1">格言编辑</el-menu-item>
              <el-menu-item index="5-2">格言列表</el-menu-item>
            </el-submenu>
          </el-menu>
        </div>
      </el-aside>
      <el-main>
        <!-- 操作区域 -->
        <div class="operation-area">
          <!-- 用户表 -->
          <div class="userTable" v-show="isShowUser">
            <el-table
              :data="usersData"
              border
              style="width: 1000px">
              <el-table-column
                fixed
                prop="user"
                label="用户名"
                width="150">
              </el-table-column>
              <el-table-column
                prop="_id"
                label="用户ID"
                width="220">
              </el-table-column>
              <el-table-column
                prop="type"
                label="用户类型"
                width="100">
              </el-table-column>
              <el-table-column
                prop="msgLimit"
                label="留言权限"
                width="100">
              </el-table-column>
              <el-table-column
                sortable
                prop="regDate"
                label="注册日期"
                width="180">
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="180">
                <template #default="scope">
                  <el-popconfirm
                    :title="setUserTableTip(scope.row, 'admin')"
                    confirmButtonText='确定'
                    cancelButtonText='取消'
                    @confirm="updateUserDetailsHandler(scope.row, 'admin')"
                  >
                  <template #reference>
                    <el-button type="text" size="small">设置管理</el-button>
                    </template>
                  </el-popconfirm>
                  <el-popconfirm
                    :title="setUserTableTip(scope.row, 'msg')"
                    confirmButtonText='确定'
                    cancelButtonText='取消'
                    @confirm="updateUserDetailsHandler(scope.row, 'msg')"
                  >
                  <template #reference>
                    <el-button  type="text" size="small">禁言设置</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 文章富文本编辑器 -->
          <div class="editor-con" v-show="isShowArticleEditor">
            <div class="editor-input">
              <el-input placeholder="* 标题" v-model="articleTitle" clearable> </el-input>
              <el-input placeholder="出处" v-model="articleSource" clearable> </el-input>
              <el-input placeholder="作者" v-model="articleAuthor" clearable> </el-input>
              <el-input placeholder="标签" v-model="articleTag" clearable> </el-input>
              <div>
                <el-radio v-model="articleClassify" label="1" border>日常</el-radio>
                <el-radio v-model="articleClassify" label="2" border>技术</el-radio>
              </div>
              <el-switch v-model="articleShare" active-text="开分享" inactive-text="关分享"></el-switch>
              <el-switch v-model="articleMsg" active-text="开留言" inactive-text="关留言"></el-switch>
            
              <div class="editor-uploader">
                <el-upload
                  class="cover-uploader"
                  :action="baseURL+'/admin/uploadCover'"
                  :show-file-list="false"
                  :with-credentials="true"
                  :on-success="handleCoverSuccess"
                >
                  <img v-if="coverPreviewURL" :src="coverPreviewURL" class="cover">
                  <i v-else class="el-icon-plus cover-uploader-icon"></i>
                </el-upload>
              </div>
            </div>

            <div class="articleEditor"></div>
            <el-button type="primary" @click="publishArticleHandler()">发布</el-button>
          </div>

          <!-- 文章管理 -->
          <div class='articleList' v-show="isShowArticleList">
            <el-table :data="articleData" style="width: 100%">
              <el-table-column fixed prop="_id" label="ID" width="150" />              
              <el-table-column prop="title" label="标题" width="300" />
              <el-table-column prop="classifyStr" label="分类" width="70" />
              <el-table-column prop="statusStr" label="状态" width="80" />
              <el-table-column fixed="right" label="操作" width="240">
                <template #default="scope">
                  <el-button 
                    size="mini" 
                    @click="offArticleHandler(scope.row, true)"
                  >
                    发布
                  </el-button>             
                  <el-button 
                    size="mini" 
                    @click="offArticleHandler(scope.row, false)"
                  >
                    下架
                  </el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="deleteArticleHandler(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="article-pager">
              <el-pagination
                layout="prev, pager, next"
                :total="totalCount"          
                :page-size="pageSize"
                background:false
                hide-on-single-page
                @current-change="curPageHandler"
                @prev-click="prevPageHandler"
                @next-click="nextPageHandler"
                @size-change="changeSizeHandler"
                @page-size="pageSizeHandler"
              >
              </el-pagination>
            </div>
          </div>

          <!-- 留言列表 -->          
          <div class="msgListTable" v-show="isShowMsgList">
            <el-table
              :data="msgData"
              style="width: 100%; margin-bottom: 20px;"
              row-key="id"
              border              
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">              
              <el-table-column
                prop="user.user"
                label="用户"
                width="150">
              </el-table-column>
              <el-table-column
                prop="_id"
                label="留言ID"
                width="220">
              </el-table-column>
              <el-table-column
                prop="section"
                label="版块"
                width="90">
              </el-table-column>
              <el-table-column
                prop="date"
                label="日期"
                sortable
                width="180">
              </el-table-column>
              <el-table-column
                prop="shieldStatus"
                label="屏蔽状态"
                width="100">
              </el-table-column>
              <el-table-column
                prop="topStatus"
                label="置顶状态"
                width="100">
              </el-table-column>
              <el-table-column
                prop="msg"
                label="留言内容"
                width="500">
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="160">
                <template #default="scope">
                  <el-popconfirm
                    :title="setMsgTableTip(scope.row, 'shield')"
                    confirmButtonText='确定'
                    cancelButtonText='取消'
                    @confirm="updateMsgDetailsHandler(scope.row, 'shield', false)"
                  >
                  <template #reference>
                    <el-button type="text" size="small">屏蔽</el-button>
                    </template>
                  </el-popconfirm>
                  <el-popconfirm
                    :title="setMsgTableTip(scope.row, 'top')"
                    confirmButtonText='确定'
                    cancelButtonText='取消'
                    @confirm="updateMsgDetailsHandler(scope.row, 'top', false)"
                  >
                  <template #reference>
                    <el-button v-show="!scope.row.childId"  type="text" size="small">置顶</el-button>
                  </template>
                  </el-popconfirm>
                  <el-button type="text" @click="deleteMsgHandler(scope.row, scope, false)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="msg-pager">
              <el-pagination
                layout="prev, pager, next"
                :total="totalCount"          
                :page-size="pageSize"
                background:false
                hide-on-single-page
                @current-change="curPageHandler"
                @prev-click="prevPageHandler"
                @next-click="nextPageHandler"
                @size-change="changeSizeHandler"
                @page-size="pageSizeHandler"
              >
              </el-pagination>
            </div>
          </div>

          <!-- 留言投诉列表 -->
          <div class="msgReportTable" v-show="isShowMsgReport">
            <el-table
              :data="msgReportData"
              style="width: 100%;margin-bottom: 20px;"
              row-key="id"
              border              
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">              
              <el-table-column
                prop="user.user"
                label="用户"
                width="150">
              </el-table-column>
              <el-table-column
                prop="_id"
                label="留言ID"
                width="220">
              </el-table-column>
              <el-table-column
                prop="section"
                label="版块"
                width="90">
              </el-table-column>
              <el-table-column
                prop="date"
                label="日期"
                sortable
                width="180">
              </el-table-column>
              <el-table-column
                prop="reportsType"
                label="投诉类型"
                width="100">
              </el-table-column>
              <el-table-column
                prop="shieldStatus"
                label="屏蔽状态"
                width="100">
              </el-table-column>              
              <el-table-column
                prop="msg"
                label="留言内容"
                width="500">
              </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="160">
                <template #default="scope">
                  <el-popconfirm
                    :title="setMsgTableTip(scope.row, 'shield')"
                    confirmButtonText='确定'
                    cancelButtonText='取消'
                    @confirm="updateMsgDetailsHandler(scope.row, 'shield', true)"
                  >
                  <template #reference>
                    <el-button type="text" size="small">屏蔽</el-button>
                    </template>
                  </el-popconfirm>                 
                  <el-button type="text" @click="deleteMsgHandler(scope.row, scope, true)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 友链管理 -->
          <div class="linkManage" v-show="isShowLinkManage">
            <el-table :data="linkData" style="width: 100%">
              <el-table-column type="expand">
                <template #default="props">
                  <el-form label-position="left" inline class="demo-table-expand">
                    <el-form-item label="博客头像">
                      <span>{{ props.row.avatar }}</span>
                    </el-form-item><br>
                    <el-form-item label="博客介绍">
                      <span>{{ props.row.introduction }}</span>
                    </el-form-item>                    
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column label="博客名称" prop="sitename" width="240"> </el-table-column>
              <el-table-column label="博客地址" prop="site" width="350"> </el-table-column>
              <el-table-column label="发布状态" prop="statusType" width="100"> </el-table-column>
              <el-table-column
                fixed="right"
                label="操作"
                width="160">
                <template #default="scope">
                  <el-button type="text" @click="setLinkStatusHandler(scope.row, true)">发布</el-button>
                  <el-button type="text" @click="setLinkStatusHandler(scope.row, false)">下架</el-button>
                  <el-button type="text" @click="deleteLinkHandler(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 经典编辑 -->
          <div class="mottoEditor" v-show="isShowMottoEditor">            
            <el-input v-model="inputMotto" placeholder="* 经典" clearable></el-input>
            <el-input v-model="inputMottoRef" placeholder="* 经典出处" clearable></el-input>
            <div>
              <el-radio v-model="radioMotto" label="1" border>儒</el-radio>
              <el-radio v-model="radioMotto" label="2" border>释</el-radio>
              <el-radio v-model="radioMotto" label="3" border>道</el-radio>
            </div>
            <el-button type="primary" @click="publishMottoHandler">发布</el-button>
          </div>

          <!-- 经典管理 -->
          <div class="mottoManage" v-show="isShowMottoManage">
            <el-table :data="mottoData" style="width: 100%">
              <el-table-column fixed prop="_id" label="ID" width="150" />
              <el-table-column prop="classify" label="分类" width="70" />
              <el-table-column prop="motto" label="经典" width="300" />
              <el-table-column prop="mottoRef" label="出处" width="150" />
              <el-table-column prop="status" label="状态" width="80" />
              <el-table-column fixed="right" label="操作" width="240">
                <template #default="scope">
                  <el-button 
                    size="mini" 
                    @click="offMottoHandler(scope.row, true)"
                  >
                    发布
                  </el-button>             
                  <el-button 
                    size="mini" 
                    @click="offMottoHandler(scope.row, false)"
                  >
                    下架
                  </el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="deleteMottoHandler(scope.row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import {mapState} from 'vuex'
import { ref } from 'vue'
import Avatar from '@/components/Avatar'
import E from "wangeditor"

export default {
  name: 'AdminPage',
  components: {Avatar},
  setup() {
    return {
      radioMotto: ref('1')
    }
  },
  data(){
    return{
      editor:'',
      activeIndex: '1-1',
      icon: require('../assets/img/logo/logo_admin.png'),
      articleTitle: '',
      articleSource: '',
      articleAuthor: '',
      articleTag: '',
      articleClassify: '1',
      articleShare: true,
      articleMsg: true,
      coverPreviewURL: '',
      coverURL: '',
      coverPrURL: '',
      inputMotto: '',
      inputMottoRef: '',
      mottoId:'',
      mottoClassify:'',
      motto:'',
      mottoRef:'',
      curPage: 0,
      pageSize: 5,  // 每页显示的条目数量
      totalCount: 0, // 留言总数
      isShowUser: true,
      isShowMsgList: false,
      isShowMsgReport: false,
      isShowLinkManage: false,
      isShowArticleEditor: false,
      isShowArticleList: false,
      isShowMottoEditor: false,
      isShowMottoManage: false,
      pagerType: 'msg',
      usersData: [],
      articleData: [],
      msgData: [],
      msgReportData: [],
      linkData: [],
      mottoData:[]
    }
  },
  computed:{
    ...mapState(['userInfo'])
  },
  async created(){
    if(!this.userInfo.user){
      // 未登录返回主页
      this.$router.replace('/')
      return
    }
    if(this.userInfo.user && !this.userInfo.isAdmin){
      // 非管理员返回主页
      this.$router.replace('/')
      return
    }
    this.reqUserList()
  },
  mounted(){
    this.editor = new E(".editor-con .articleEditor")    
    this.editor.config.height = 300
    this.editor.config.menuTooltipPosition = 'down'

    this.editor.config.uploadImgMaxSize = 10 * 1024 * 1024 // 将图片大小限制为 10M
    this.editor.config.uploadImgMaxLength = 1 // 限制一次最多上传 1 张图片

    //监听函数在上传图片的不同阶段做相应处理
    this.editor.config.customUploadImg = async (resultFiles, insertImgFn) => {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法    
      
      let formData = new FormData()
      formData.append('articleImg', resultFiles[0])

      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/uploadImg',
        data: formData
      })

      if(data.code){
        return this.$message.error(data.msg)
      }

      let imgURL = this.baseURL + data.data.url
      // 上传图片，返回结果，将图片插入到编辑器中
      insertImgFn(imgURL)
    }

    this.editor.create()
  },
  methods:{    
    // 左侧导航选择
    handleSelect(key, keyPath){
      // console.log(key, keyPath)
      this.isShowUser = false
      this.isShowMsgList = false
      this.isShowMsgReport = false
      this.isShowLinkManage = false
      this.isShowArticleEditor = false
      this.isShowArticleList = false
      this.isShowMottoEditor = false
      this.isShowMottoManage = false
      switch(key){
        case "1-1":
          this.isShowUser = true
          this.reqUserList()
          break
        case "2-1":
          this.isShowArticleEditor = true
          break
        case "2-2":
          this.curPage = 0
          this.pagerType = 'article'
          this.isShowArticleList = true
          this.reqArticleList()
          break
        case "3-1":
          this.curPage = 0
          this.pagerType = 'msg'
          this.isShowMsgList = true
          this.reqMsgList()
          break
        case "3-2":
          this.isShowMsgReport = true
          this.reqMsgReportList()
          break
        case "4":
          this.isShowLinkManage = true
          this.reqLinkList()
          break
        case "5-1":
          this.isShowMottoEditor = true
          break
        case "5-2":
          this.isShowMottoManage = true
          this.reqMottoList()
          break
      }
    },
    // 发布经典
    async publishMottoHandler(){
      // console.log("publishMottoHandler");
      // inputMotto,inputMottoRef
      if(!this.inputMotto || !this.inputMottoRef){
        return this.$message.error('经典和出处不能为空')
      }
      // console.log(this.radioMotto);
      let {data} = await this.$axios({
        method: 'post',
        url: 'admin/publishMotto',
        data: {
          motto: this.inputMotto,
          mottoRef: this.inputMottoRef,
          classify: +this.radioMotto
        }
      })
      if(data.code){
        return this.$message.error(data.msg)
      }
      // console.log(data);
      this.$message.success(data.msg)
    },
    // 获取经典列表
    async reqMottoList(){
      let { data } = await this.$axios({
        method: 'post',
        url: '/admin/mottoList'
      })
      data.data.map(item => {
        if(item.classify === 1){
          item.classify = '儒'
        }else if(item.classify === 2){
          item.classify = '释'
        }else{
          item.classify = '道'
        }
        if(item.status === 1){
          item.status = '上架中'
        }else{
          item.status = '已下架'
        }
      })
      this.mottoData = data.data
    },
    // 设置经典状态（上架or下架）
    async offMottoHandler(itemData, status){
      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/offMotto',
        data: {
          _id: itemData._id,
          status
        }
      })

      if(data.code){
        return this.$message.error(data.msg)
      }

      this.reqMottoList()
      this.$message.success(data.msg)
    },
    // 删除经典
    deleteMottoHandler(itemData){
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let {data} = await this.$axios({
          method: 'post',
          url: '/admin/mottoDelete',
          data:{
            _id: itemData._id
          }
        })
        if(data.code){
          return this.$message.error(data.msg)
        }

        this.reqMottoList()
        this.$message.success('删除成功！')
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    },
    // 封面上传成功回调
    handleCoverSuccess(res, file){
      if(res.code){
        return this.$message.error(res.msg)
      }
      this.coverPreviewURL = URL.createObjectURL(file.raw)
      this.coverURL = res.data.url
      this.coverPrURL = res.data.coverPrUrl
      // console.log(this.coverURL)
      //提示成功
      this.$message.success('封面图片上传成功')
    },
    // 发布文章
    async publishArticleHandler(){
      // console.log(this.editor.txt.html())
      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/uploadArticle',
        data: {
          title: this.articleTitle,
          content: this.editor.txt.html(),
          source: this.articleSource,
          classify: +this.articleClassify,
          cover: this.coverURL,
          coverPr: this.coverPrURL,
          author: this.articleAuthor,
          tag: this.articleTag,
          message: this.articleMsg,
          share: this.articleShare
        }
      })

      if(data.code){
        return this.$message.error(data.msg)
      }
      this.$message.success(data.msg)
    },
    // 获取html里的img.src
    getImgSrc(htmlstr){
      let urls = []
      htmlstr.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi,  (match, capture) => {
        urls.push(capture)
      });
      if(urls.length === 0) return ''
      let firstImg = urls[0]
      let arr = firstImg.split("/")
      return arr[arr.length - 1]
    },
    // 设置友链状态
    async setLinkStatusHandler(item, status){
      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/setLinkStatus',
        data: {
          _id: item._id,
          status
        }
      })

      if(data.code){
        return this.$message.error(data.msg)
      }

      this.reqLinkList()
      this.$message.success(data.msg)
    },
    // 删除友链
    async deleteLinkHandler(item){
      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/linkDelete',
        data: {
          _id: item._id
        }
      })

      if(data.code){
        return this.$message.error(data.msg)
      }
      
      this.reqLinkList()
      this.$message.success(data.msg)
    },
    // 请求友链列表
    async reqLinkList(){
      let { data } = await this.$axios({
        method: 'post',
        url: '/admin/getLinks'
      })

      data.data.map(item => {
        if(item.status === 0){
          item.statusType = '下架中'
        }else{
          item.statusType = '已发布'
        }
      })
      this.linkData = data.data
    },
    // 请求留言投诉列表
    async reqMsgReportList(){
      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/msgReportList',
        data:{
          curPage: 0,
          pageSize: 5
        }
      })
      
      data.data.map(item => {
        this.formatMsgData(item)
      })
      // console.log(data.data);
      this.msgReportData = data.data
    },
    // 删除留言
    deleteMsgHandler(msgData, scope, isReport){
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let {data} = await this.$axios({
          method: 'post',
          url: '/admin/deleteSingleMsg',
          data:{
            _id: msgData.parentId,
            childId: msgData.childId
          }
        })
        if(data.code){
          return this.$message.error(data.msg)
        }

        if(isReport){
          this.reqMsgReportList()
        }else{
          this.reqMsgList()
        }        
        this.$message.success('删除成功！')
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    },    
    // 更改留言属性
    async updateMsgDetailsHandler(itemData, type, isReport){
      let isShield,isTop
      if(type === "shield"){
        isShield = !itemData.isShield
        isTop = itemData.isTop ? 1 : 0
      }else if(type === "top"){
        isTop = !itemData.isTop ? 1 : 0
        isShield = itemData.isShield
      }

      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/setMsg',
        data: {
          _id: itemData.parentId,
          childId: itemData.childId,
          isShield,
          isTop
        }
      })

      if(data.code){
        return this.$message.error(data.msg)
      }

      if(isReport){
        this.reqMsgReportList()
      }else{
        this.reqMsgList()
      }
      
      if(type === "shield"){
        this.$message.success('屏蔽操作成功')
      }else if(type === "top"){
        this.$message.success('置顶操作成功')
      }
    },
    // 更改留言管理的提示文字
    setMsgTableTip(data, type){
      if(type === "shield"){
        if(data.isShield){
          return '取消屏蔽？'
        }else{
          return '屏蔽该留言？'
        }
      }else if(type === "top"){
        if(data.isTop){
          return '取消置顶？'
        }else{
          return '置顶该留言？'
        }
      }
    },

    // 文章 上/下架
    async offArticleHandler(itemData, status){
      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/offArticle',
        data: {
          _id: itemData._id,
          status
        }
      })

      if(data.code){
        return this.$message.error(data.msg)
      }

      this.reqArticleList()
      this.$message.success(data.msg)
    },

    // 文章删除
    deleteArticleHandler(itemData){
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let {data} = await this.$axios({
          method: 'post',
          url: '/admin/articleDelete',
          data:{
            _id: itemData._id
          }
        })
        if(data.code){
          return this.$message.error(data.msg)
        }

        this.reqArticleList()
        this.$message.success('删除成功！')
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      });
    },

    // 获取文章列表
    async reqArticleList(){
      let {data} = await this.$axios({
        method: 'post',
        url: '/article/adminList',
        data: {
          curPage: this.curPage,
          pageSize: this.pageSize
        }
      })

      this.articleData = data.data.list
      this.totalCount = data.data.totalCount
      this.formatArticleData(this.articleData)      
    },

    // 获取留言列表
    async reqMsgList(){
      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/msgList',
        data:{
          curPage: this.curPage,
          pageSize: this.pageSize,
        }
      })
      
      let list = data.data.list
      list.map(item => {
        this.formatMsgData(item)
      })
      this.msgData = list
      this.totalCount = data.data.totalCount
      // console.log(this.msgData);
    },
    // 更改用户属性
    async updateUserDetailsHandler(itemData, type) {
      let adminValue, msgValue
      if(type === "admin"){
        adminValue = !itemData.isAdmin
        msgValue = itemData.msgPermissions
      }else if(type === "msg"){
        msgValue = !itemData.msgPermissions
        adminValue = itemData.isAdmin
      }
      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/setUser',
        data:{
          _id: itemData._id,
          isAdmin: adminValue,
          msgPermissions: msgValue
        }
      })
      
      if(data.code){
        return this.$message.error(data.msg)
      }
      
      this.reqUserList()
      if(type === "admin"){
        this.$message.success('管理员设置操作成功')
      }else if(type === "msg"){
        this.$message.success('用户留言权限操作成功')
      }      
    },
    // 请求用户列表
    async reqUserList(){      
      let {data} = await this.$axios({
        method: 'post',
        url: '/admin/allUser'
      })

      data.data.map(item => {
        this.formatUserData(item)
      })
      this.usersData = data.data
    },
    // 更改用户管理的提示文字
    setUserTableTip(data, type){
      if(type === "admin"){
        if(data.isAdmin){
          return '取消 '+ data.user +' 为管理员'
        }else{
          return '设置 '+ data.user +' 为管理员'
        }
      }else{
        if(data.msgPermissions){
          return '设置 '+ data.user + ' 用户禁言'
        }else{
          return '取消 ' + data.user +' 用户禁言'
        }
      }
    },
    // 处理文章数据
    formatArticleData(articleData){
      articleData.map(item => {
        if(item.classify === 1){
          item.classifyStr = '日常'
        }else if(item.classify === 2){
          item.classifyStr = '技术'
        }
        if(item.status === 1){
          item.statusStr = '发布中'
        }else if(item.status === 0){
          item.statusStr = '已下架'
        }
      })
    },
    // 处理留言数据
    formatMsgData(msgData){
      if(msgData.isShield){
        msgData.shieldStatus = '已屏蔽'
      }else{
        msgData.shieldStatus = '普通'
      }
      if(msgData.isTop){
        msgData.topStatus = '已置顶'
      }else{
        msgData.topStatus = '普通'
      }

      msgData.reportsType = []
      msgData.reports.map(type => {
        // console.log("reports.type:", type);
        switch(type){
          case 1:
            msgData.reportsType.push("违法违规")
            break
          case 2:
            msgData.reportsType.push("不友善")
            break
          case 3:
            msgData.reportsType.push("灌水")
            break
          case 4:
            msgData.reportsType.push("广告")
            break
        }
      })

      msgData.children.map(item => {
        if(item.isShield){
          item.shieldStatus = '已屏蔽'
        }else{
          item.shieldStatus = '普通'
        }
        if(item.isTop){
          item.topStatus = '已置顶'
        }else{
          item.topStatus = '普通'
        }

        item.reportsType = []
        item.reports.map(type => {
          switch(type){
            case 1:
              item.reportsType.push("违法违规")
              break
            case 2:
              item.reportsType.push("不友善")
              break
            case 3:
              item.reportsType.push("灌水")
              break
            case 4:
              item.reportsType.push("广告")
              break
          }
        })

        item.parentId = msgData._id
        item.childId = item._id        
        item.date = this.formatDate(item.date)
      })

      msgData.parentId = msgData._id
      msgData.date = this.formatDate(msgData.date)
    },
    // 处理用户数据
    formatUserData(userItem){
      if(userItem.isAdmin){
        userItem.type = '管理员'
      }else{
        userItem.type = '普通用户'
      }
      if(userItem.msgPermissions){
        userItem.msgLimit = '正常'
      }else{
        userItem.msgLimit = '禁言'
      }
      userItem.regDate = this.formatDate(userItem.regDate)
    },
    // 当前页
    curPageHandler(cpage){
      this.getShowList(cpage)
    },
    // 上一页
    prevPageHandler(cpage){
      this.getShowList(cpage)
    },
    // 下一页
    nextPageHandler(cpage){
      this.getShowList(cpage)
    },
    // 根据当前页请求留言数据
    getShowList(cpage){
      this.curPage = cpage - 1
      if(this.pagerType === 'msg'){
        this.reqMsgList()
      }else if(this.pagerType === 'article'){
        this.reqArticleList()
      }
    },
    //处理时间格式
    formatDate(val) {
      let date = new Date(val),
        YY = date.getFullYear(),
        MM = date.getMonth() + 1,
        DD = date.getDate(),
        hh = date.getHours(),
        mm = date.getMinutes(),
        ss = date.getSeconds()

      hh < 10 && (hh = '0' + hh)
      mm < 10 && (mm = '0' + mm)
      ss < 10 && (ss = '0' + ss)

      return `${YY}年${MM}月${DD}日 ${hh}:${mm}:${ss}`
    },
    changeSizeHandler(curSize){      
    },
    pageSizeHandler(){
    },
  }
}
</script>

<style lang="less" scoped>
  @topHeight: 66px;
  
  .el-header, .el-footer {
    background-color: #B3C0D1;
    color: var(--el-text-color-primary);
    text-align: center;
    line-height: 60px;
  }

  .el-aside {
    background-color: #545c64;
    color: var(--el-text-color-primary);
    text-align: center;
    line-height: 200px;
    width: 200px;    
  }

  .el-main {
    background-color: #E9EEF3;
    color: var(--el-text-color-primary);
    text-align: center;
    line-height: 50px;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }

  #AdminPage{
    width: 100%;
    height: 100%;
    background-color: #545C64;
    .top{
      width: 100%;
      height: @topHeight;
      background-color: #010f22;
      .content{
        display: flex;
        justify-content: space-between;
        width: 1200px;
        height: @topHeight;
        margin: 0 auto;
        .title{
          img{
            width: 50px;
            height: 50px;
            vertical-align: -13px;
          }
          font-size: 28px;
          color: #fff;
          line-height: @topHeight;
        }
      }
    }

    .content{
      display: flex;
      .nav{
        width: 200px;
        margin-left: 1px;
      }
      .operation-area{
        flex: 1;
        background-color: #fff;

        .editor-con{
          .editor-input{
            display: flex;
            flex-wrap: wrap;
            .el-radio{
              margin: 15px 10px;
            }
            .el-input{
              width: 180px;
              margin: 10px;
            }
            .el-switch{
              margin: 10px 15px;
            }

            .editor-uploader{
              /deep/ .cover-uploader .el-upload {
                border: 1px dashed #d9d9d9;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                float: left;
              }
              .cover-uploader .el-upload:hover {
                border-color: #409EFF;
              }
              .cover-uploader-icon {
                font-size: 28px;
                color: #8c939d;
                width: 178px;
                height: 178px;
                line-height: 178px;
                text-align: center;
              }
              .cover {
                width: 178px;
                height: 178px;
                display: block;
              }
            }
          }
        }

        .articleList{
          .article-pager{
            margin-top: 50px;
          }
        }        
        .msgListTable{
          .msg-pager{
            margin-top: 50px;
          }
        }

        .mottoEditor{
          padding: 20px;
        }
      }
    }
  }

  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }

  /deep/ .el-pagination .btn-next, .el-pagination .btn-prev{
    background-color: transparent;
  }

  /deep/ .el-pagination button:disabled{
    background-color: transparent;
  }

  /deep/ .el-pager li{
    background-color: transparent;
  }

  /deep/ .el-pagination .btn-prev{
    background-color: transparent;
  }
</style>